<template>
  <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入活动名称" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="活动主图" prop="picUrl">
          <div>
            <UploadImg v-model="formData.picUrl" width="80px" height="80px" />
          </div>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="活动时间" prop="startAndEndTime">
          <el-date-picker
            v-model="formData.startAndEndTime"
            :end-placeholder="t('common.endTimeText')"
            :start-placeholder="t('common.startTimeText')"
            range-separator="-"
            type="datetimerange"
            value-format="x"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="参与渠道" prop="salesChannel">
          <el-checkbox-group v-model="formData.salesChannel">
            <template
              v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_SALES_CHANNEL)"
              :key="dict.value"
            >
              <el-checkbox :value="dict.value" v-if="dict.value != 4">{{ dict.label }}</el-checkbox>
            </template>
          </el-checkbox-group>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="销售门店" v-if="formData.salesChannel?.includes(1)">
          <div class="w-100%">
            <el-radio-group :model-value="1">
              <el-radio :value="1">选择门店</el-radio>
            </el-radio-group>
            <div
              class="p-10px w-100% border-rd-5px border-1px bg-[var(--el-color-primary-light-9)]"
            >
              <StoreSelect v-model="formData.authorizedTenant">添加销售门店 </StoreSelect>
            </div>
          </div>
        </el-form-item>
      </el-col>
    </el-row>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center justify-between bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>活动规则</span>
      <el-button class="mr-15px" @click="attributesAddFormOpen">添加规则</el-button>
    </div>
    <!-- <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="线上渠道" v-if="formData.salesChannel?.includes(2)">
          <div class="w-100%">
            <el-checkbox-group v-model="formData.salesOnlineChannel">
              <el-checkbox
                v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_SALES_ONLINE_CHANNEL)"
                :key="dict.value"
                :value="dict.value"
                >{{ dict.label }}</el-checkbox
              >
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-col>
    </el-row> -->
    <el-row>
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-form-item label="活动商品" prop="spuId">
          <el-button @click="giveGoodsSelectRef.open()">选择商品</el-button>
          <SkuList
            class="mt-20px"
            ref="skuListRef"
            :isComponent="false"
            :isDetail="false"
            :prop-form-data="spuData"
            :rule-config="ruleConfig"
          >
            <template #extension>
              <el-table-column align="center" label="必选" min-width="90">
                <template #default="{ row }">
                  <el-switch v-model="row.productConfig.selected" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="优惠方式" min-width="90">
                <template #default="{ row }">
                  <el-select v-model="row.productConfig.discountType" placeholder="请选择">
                    <el-option label="折扣" :value="2" />
                    <el-option label="优惠" :value="1" />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column align="center" label="活动价" min-width="168">
                <template #default="{ row }">
                  <el-input-number
                    class="w-100%!"
                    v-model="row.productConfig.discountPercent"
                    :precision="2"
                    :max="100"
                    v-if="row.productConfig.discountType == 2"
                  >
                    <template #suffix> %</template>
                  </el-input-number>
                  <el-input-number
                    class="w-100%!"
                    v-model="row.productConfig.discountPrice"
                    :max="parseFloat(row.price)"
                    :precision="2"
                    v-else
                  >
                    <template #suffix> 元 </template>
                  </el-input-number>
                </template>
              </el-table-column>
              <el-table-column align="center" label="活动最低价" min-width="168">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.productConfig.activityProductLowPrice"
                    :max="100"
                    :min="0"
                    :precision="2"
                    :step="0.1"
                    class="w-100%"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="数量" min-width="168">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.productConfig.activityProductCount"
                    :min="0"
                    :precision="0"
                    class="w-100%"
                  />
                </template>
              </el-table-column>
            </template>
          </SkuList>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="活动规则" prop="price">
          <div class="flex w-100%">
            <div class="flex-1">
              <el-form-item prop="price">
                <el-input-number
                  class="w-100%!"
                  v-model="formData.price"
                  :precision="2"
                  :controls="false"
                >
                  <template #suffix> 元 </template>
                </el-input-number>
              </el-form-item>
            </div>
            <div class="mx-10px"> 任选 </div>
            <div class="flex-1">
              <el-form-item prop="number">
                <el-input-number
                  class="w-100%!"
                  v-model="formData.number"
                  :precision="0"
                  :max="spuData.skus?.length || 0"
                  :controls="false"
                >
                  <template #suffix> 类 </template>
                </el-input-number>
              </el-form-item>
            </div>
          </div>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-form-item label="抵扣设置">
          <div class="w-100%">
            <el-checkbox-group v-model="formData.discountScopes">
              <el-checkbox
                v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_NTON_TYPES)"
                :key="dict.value"
                :value="dict.value"
                >{{ dict.label }}</el-checkbox
              >
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row v-if="formData.salesChannel?.includes(1)">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-form-item label="修改设置">
          <div class="w-100%">
            <el-checkbox v-model="formData.isUpdated">允许门店修改 </el-checkbox>
          </div>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <GiveGoodsSelect ref="giveGoodsSelectRef" :isSelectSku="true" @confirm="selectSku" />
  <!-- 商品规则添加 Form 表单 -->
  <ProductPropertyAddForm ref="attributesAddFormRef" @success="generateSkus" />
</template>
<script lang="ts" setup>
import SkuList from '@/views/mall/product/components/SkuList.vue'
const { t } = useI18n() // 国际化

import { cloneDeep } from 'lodash-es'
import * as NChooseNActivityApi from '@/api/mall/promotion/nChooseN/nChooseNActivity'
import * as ProductSpuApi from '@/api/shop/product/spu'

import GiveGoodsSelect from '@/views/mall/product/components/GiveGoodsSelect.vue'
import { RuleConfig } from '@/views/mall/product/spu/components'
import { fenToYuan, copyValueToTarget, floatToFixed2, yuanToFen } from '@/utils'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

defineOptions({ name: 'NChooseNActivityForm' })
const props = defineProps({
  propFormData: {
    type: Object as PropType<NChooseNActivityApi.NChooseNActivityVO>,
    default: () => {}
  }
})

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formRef = ref() // 表单 Ref
const formData = reactive<NChooseNActivityApi.NChooseNActivityVO>({
  name: undefined,
  startAndEndTime: [],
  remark: undefined,
  salesChannel: [], //参与渠道
  price: undefined, //活动规则
  number: undefined, // 活动数量
  discountScopes: [], //抵扣设置
  authorizedTenant: [], //关联门店
  salesOnlineChannel: [], //线上渠道
  products: [],
  picUrl: undefined, //活动主图
  isUpdated: false,
  startTime: undefined,
  endTime: undefined
})

const formRules = reactive({
  name: [required],
  price: [required],
  number: [required],
  startAndEndTime: [required],
  discountType: [required]
})
// ================= 商品选择相关 =================

const giveGoodsSelectRef = ref() // 商品和属性选择 Ref
const skuListRef = ref() // sku   配置组件Ref
const ruleConfig: RuleConfig[] = [
  // {
  //   name: 'productConfig.discountPrice',
  //   rule: (arg) => arg > 0,
  //   message: '商品优惠金额不能为 0 ！！！'
  // }
]
const selectSku = (skuIds: number[]) => {
  getSkuDetails(skuIds)
}
const attributesAddFormRef = ref() // 添加商品属性表单

const attributesAddFormOpen = () => {
  attributesAddFormRef.value.open()
}
/** 调用 SkuList generateTableData 方法*/
const generateSkus = (propertyList: any[]) => {
  console.log(propertyList)
}
/** 获取SKU详情 */
const spuData = ref({
  skus: []
}) //为了统一组件格式
const getSkuDetails = async (
  skuIds: number[] | undefined,
  products?: NChooseNActivityApi.DiscountProductVO[]
) => {
  const data = await ProductSpuApi.getSkuPageList2({ skuIds } as any)
  if (data.list.length == 0) {
    return
  }
  data.list.forEach((sku) => {
    let config: NChooseNActivityApi.DiscountProductVO = {
      skuId: sku.skuId!,
      spuId: sku.spuId!,
      discountPrice: undefined,
      discountType: 1,
      discountPercent: undefined,
      activityProductLowPrice: undefined,
      activityProductCount: 0,
      selected: false
    }
    if (typeof products !== 'undefined') {
      const product = products.find((item) => item.skuId === sku.skuId)
      if (product) {
        product.activityProductLowPrice = fenToYuan(product.activityProductLowPrice!) as any
        product.discountPrice = fenToYuan(product.discountPrice!) as any
      }
      config = product || config
    }
    sku.productConfig = config
    sku.price = floatToFixed2(sku.price)
    sku.lowPrice = floatToFixed2(sku.lowPrice)
  })
  spuData.value.skus = data.list
}

/**
 * 获取所有 sku 活动配置
 *
 * @param extendedAttribute 在 sku 上扩展的属性，例：秒杀活动 sku 扩展属性 productConfig 请参考 seckillActivity.ts
 */
const getSkuConfigs = (extendedAttribute: string) => {
  skuListRef.value.validateSku()
  const products: any[] = []
  spuData.value.skus?.forEach((sku: any) => {
    products.push(sku[extendedAttribute] as any)
  })
  return products
}
// ================= end =================

/** 提交表单 */

const validate = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await unref(formRef)?.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    // skuListRef.value.validateSku()

    // 获取折扣商品配置
    const products = cloneDeep(getSkuConfigs('productConfig'))

    products.forEach((item: NChooseNActivityApi.DiscountProductVO) => {
      item.activityProductLowPrice = yuanToFen(item.activityProductLowPrice!)
      item.discountPrice = yuanToFen(item.discountPrice!)
    })
    const data = cloneDeep(formData) as NChooseNActivityApi.NChooseNActivityVO
    data.products = products
    Object.assign(props.propFormData, data)

    // 发送操作成功的事件
  } finally {
    formLoading.value = false
  }
}
defineExpose({ validate })

/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  async (data) => {
    if (!data) {
      return
    }
    await getSkuDetails(
      data.products?.map((sku) => sku.skuId),
      data.products
    )
    copyValueToTarget(formData, data)
  }
)

onMounted(async () => {})
</script>
